<?php
namespace Swiftx\Bundle\WeChat\Controller\Mall;
use Swiftx\Bundle\WeChat\Factory\Company as CompanyFactory;
use Swiftx\Bundle\WeChat\Factory\Goods as GoodsFactory;
use Swiftx\Bundle\WeChat\Interfaces\Common\AjaxController;
use Swiftx\Bundle\WeChat\Interfaces\Controller\Mall\Goods as GoodsInterface;
use Swiftx\Bundle\WeChat\Model\Mall\Attribute;
use Swiftx\Bundle\WeChat\Model\Mall\Goods as GoodsModel;
use Swiftx\Bundle\WeChat\Model\Mall\Image;
use Swiftx\Bundle\WeChat\Model\Mall\Spec;
use Swiftx\Interfaces\Httpd\Request;
use Swiftx\Interfaces\Httpd\Response;

/**
 * 用户登录页面实现
 */
class Goods extends AjaxController implements GoodsInterface{

    /**
     * 企业工厂实例
     * @var CompanyFactory
     * @auto-injection
     */
    protected $companyFactory;

    /**
     * 企业工厂实例
     * @var GoodsFactory
     * @auto-injection
     */
    protected $goodsFactory;

    /**
     * 新增商品记录
     * @param Request   $request
     * @param Response  $response
     * @router method   get
     * @return bool
     */
    public function create(Request $request, Response $response): bool{
        $company = $this->companyFactory->currentLogin($request);
        $post = $request->getPost();

        /** @var GoodsModel $new_goods */
        $new_goods = $this->container->create(GoodsModel::class);
        $new_goods->setCompany($company->getID());

        // 设置商品基本数据
        $new_goods->setTitle($post->get('title'));
        $new_goods->setDescription($post->get('description'));
        $new_goods->setNumber($post->get('number'));
        $new_goods->setInvoice($post->get('invoice'));
        $new_goods->setGuarantee($post->get('guarantee'));
        $new_goods->setIsReturn($post->get('isReturn'));
        $new_goods->setLogisticsDistribution($post->get('logisticsDistribution'));
        $new_goods->setLogisticsSelf($post->get('logisticsSelf'));

        // 设置商品上架数据
        if($post->get('shelving') == 'current')
            $new_goods->setSellTimeStamp(time());
        else if($post->get('shelving') == 'none')
            $new_goods->setSellTimeStamp(0);
        else $new_goods->setSellTimeStamp(strtotime($post->get('shelving')));
        $this->entityManager->save($new_goods);

        // 添加商品图片关联
        foreach ($post->get('albums') as $value){
            /** @var Image $new_album */
            $new_album = $this->container->create(Image::class);
            $new_album->setGoodsID($new_goods->getID());
            $new_album->setImage($value);
            $this->entityManager->save($new_album);
        }

        // 添加参数关联
        foreach ($post->get('specs') as $value){
            /** @var Spec $new_spec */
            $new_spec = $this->container->create(Spec::class);
            $new_spec->setGoodsID($new_goods->getID());
            $new_spec->setName($value['name']);
            $new_spec->setPrice($value['price']);
            $new_spec->setStock($value['stock']);
            $this->entityManager->save($new_spec);
        }

        // 添加属性关联
        foreach ($post->get('params') as $value){
            /** @var Attribute $new_attr */
            $new_attr = $this->container->create(Attribute::class);
            $new_attr->setGoodsID($new_goods->getID());
            $new_attr->setName($value['name']);
            $new_attr->setValue($value['value']);
            $this->entityManager->save($new_attr);
        }

        // 执行数据写入
        $this->entityManager->flush();
        // 返回执行结果
        return $this->successDisplay($response, [
            'id' => $new_goods->getID()
        ]);
    }

    /**
     * 显示商品列表
     * @param Request $request
     * @param Response $response
     * @return bool
     */
    public function ajaxList(Request $request, Response $response):bool{
        // 获取查询对象设置企业关联
        $company = $this->companyFactory->currentLogin($request);
        $query = $this->entityManager->builder(GoodsModel::class);
        $query->conditionEqualString('company', $company->getID());

        // 设置查询的商品出售状态
        if($request->hasParam('sale')) {
            $value = $request->getParam('sale');
            if($value == 'true')
                $query->conditionEqualLtInt('sellTime', time());
            else if($value == 'false')
                $query->conditionEqualInt('sellTime', 0);
        }

        // 设置查询关键词
        $keyword = $request->getParam('keyword');
        if(!empty($keyword))
            $query->conditionLike('title', '%'.$keyword.'%');

        // 分页数据条件
        $currentPage = $request->getParam('page', 1);
        $capacity = $request->getParam('capacity', 20);

        $page = $query->page($currentPage, $capacity);
        $result['list'] = [];
        $result['total'] = $page->getTotal();

        /** @var GoodsModel $goods */
        foreach ($page->getData() as $goods){
            $result['list'][] = [
                'id' => $goods->getID(),
                'title' => $goods->getTitle(),
                'image' => $goods->getImage()->getUrl(),
                'stock' => $goods->getStock(),
                'price' => [
                    'max' => $goods->getMaxPrice(),
                    'min' => $goods->getMinPrice()
                ],
                'time' => $goods->getCreateTimeFormat()
            ];
        }

        // 响应查询结果
        return $this->successDisplay($response, $result);
    }

    /**
     * 显示商品详情
     * @param Request $request
     * @param Response $response
     * @return bool
     */
    public function ajaxDetail(Request $request, Response $response):bool{

        return true;
    }

    /**
     * 显示商品详情
     * @param Request $request
     * @param Response $response
     * @return bool
     */
    public function ajaxBuy(Request $request, Response $response):bool{

        return true;
    }


}